//
//  SearchViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchModel.h"
#import "NetWorkingTool.h"
#import "MusicPlayViewController.h"     //播放页面
#import "BaseModel.h"   // 基类 model
#import "PlayerSingleton.h"
#import "MJRefresh.h"
#import "NightMode.h"
#import "AFNetworkReachabilityManager.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate , UIAlertViewDelegate>

//@property (nonatomic , retain)AVPlayerItem *playerItem;
@property (nonatomic , copy)NSString *str;
@property (nonatomic , assign)NSInteger number;
@property (nonatomic, retain)UITableViewCell *cell;
@property (nonatomic , assign)BOOL result;
@property(nonatomic, retain)UIImageView *backgroundView;


@end

@implementation SearchViewController

- (void)dealloc
{
    [_cell release];
    [_str release];
    [_modelArr release];
    [_tableView release];
    [_player release];
    [_searchBar release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.modelArr = [NSMutableArray array];
    }
    
    return self;
}
- (void)data
{
    if (![self.searchBar.text isEqualToString:@""]) {
        NSString *strHead = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?q=%@" , self.searchBar.text];
        NSString *strUrl = [NSString stringWithFormat:@"%@&page=1&size=50&app=ttpod&v=v7.7.0.2015012818&uid=&mid=iPhone4&f=f320&s=s310&imsi=&hid=&splus=7.1.1&active=1&net=2&openudid=ad6f50f586818c4f36ff4358053c1b53fee58cdf&idfa=E2EAC64B-1F1C-4AC5-A0E1-8BE37A03FB96&utdid=VTCyBQSkYzwDAALO9zZTFfPC&alf=201200" , strHead];
        [NetWorkingTool netWorkingToolStr:strUrl block:^(id result) {
            NSMutableDictionary *dic = result;
            NSMutableArray *arr = [dic objectForKey:@"data"];
            [self.modelArr removeAllObjects];
            for (NSInteger i = 0; i < arr.count ; i++) {
                BaseModel *baseModel = [[BaseModel alloc]init];
                baseModel.song_name = arr[i] [@"song_name"];
                baseModel.singer_name = arr[i] [@"singer_name"];
                baseModel.songe_url = arr[i][@"audition_list"][0][@"url"];
                baseModel.song_time = arr[i][@"audition_list"][0][@"duration"];
                [self.modelArr addObject:baseModel];
                [baseModel release];
            }
            [self.tableView reloadData];
        }];
    }else
    {
//        [self.modelArr removeAllObjects];
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 100)];
    self.backgroundView.image = [UIImage imageNamed:@"searchBackground"];
    [self.view addSubview:self.backgroundView];
    [self.backgroundView release];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    self.title = @"搜索";
    // Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, HEIGHT / 667 * 50, WIDTH, HEIGHT / 667 * (667-113-50)) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
//    [self.tableView addSubview:backgroundView];
    [_tableView release];
    // 判断是不是夜间模式
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }

    
    
    // 创建searchBar
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT / 667 * 50)];
    self.searchBar.delegate = self;
    [self.view addSubview:self.searchBar];
    [_searchBar release];
    
    //autocapitalizationType----- 自动对输入文本对象进行大小写设置
    self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeWords;
    //autocorrectionType --------- 自动纠正输入文本错误
    self.searchBar.autocorrectionType = UITextAutocorrectionTypeYes;
    // 搜索 光标改变颜色
    self.searchBar.tintColor = [UIColor purpleColor];
    // 搜索背景颜色
    self.searchBar.backgroundColor = [UIColor whiteColor];
    // 改变 搜索条 下边的颜色,也是背景
//    self.searchBar.barTintColor = [UIColor cyanColor];
    //
    self.searchBar.translucent = NO;
    //
    self.searchBar.showsScopeBar = YES;
    self.searchBar.showsCancelButton = YES;
//    self.searchBar.showsSearchResultsButton = YES;
    self.searchBar.placeholder = @"搜索内容";
    
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                self.result = NO;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [self alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                self.result = YES;
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
}

- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机自带网络" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
}


//  搜索 方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (self.result == YES) {
        [self data];
    }
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.location > 100) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"亲~你吃炫迈了么???" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    if (self.result == YES) {
        
        [self data];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}




#pragma mark tableView的 两个协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 判断是不是夜间模式
    
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }
    static NSString *reuse = @"reuse";
    self.cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (self.cell == nil) {
        self.cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
        self.number = indexPath.row;
        BaseModel *model = self.modelArr[indexPath.row];
    self.cell.backgroundColor = [UIColor clearColor];
        self.cell.textLabel.text = model.song_name;
        self.cell.detailTextLabel.text = model.singer_name;
        return self.cell;
  
  }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.searchBar resignFirstResponder];
    MusicPlayViewController *musicVC = [[MusicPlayViewController alloc]init];
    musicVC.modelArr = self.modelArr;
    musicVC.indexPath = indexPath.row;
    [self.navigationController pushViewController:musicVC animated:YES];
    [musicVC release];

}
- (void)setLightDayModel
{
    self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.backgroundView.image = [UIImage imageNamed:@"searchBackground"];
    self.cell.textLabel.textColor = [UIColor blackColor];
    self.cell.detailTextLabel.textColor = [UIColor blackColor];
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
}

- (void)setNightDayModel
{
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];

    self.backgroundView.image = [UIImage imageNamed:@"nightSearchBackground"];
    self.backgroundView.alpha = 0.9;
    self.cell.textLabel.textColor = [UIColor whiteColor];
    self.cell.detailTextLabel.textColor = [UIColor whiteColor];

    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;


}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
